package core.proto.vis.action;

import java.util.Iterator;

import javax.swing.SwingUtilities;

import prefuse.Visualization;
import prefuse.action.GroupAction;
import prefuse.data.Graph;
import prefuse.data.Node;
import prefuse.data.tuple.TupleSet;
import core.proto.AllComponents;
import core.proto.FileTree;
import core.util.logging.UserLogWriter;

public class FileOpenAction extends GroupAction
{
    public FileOpenAction( String group ) {
        super( group );
    }

    @SuppressWarnings("static-access")
    @Override
    public void run( double frac ) {
        TupleSet focus = m_vis.getGroup( Visualization.FOCUS_ITEMS );
        if( focus == null || focus.getTupleCount() == 0 )
            return;

        Graph g = (Graph) m_vis.getGroup( m_group );
        Node f = null;
        Object o = null;
        @SuppressWarnings("rawtypes")
        Iterator tuples = focus.tuples();
        while( tuples.hasNext() ) {
            o = tuples.next();
            // if o is not a node or it's not part of the graph
            if( !(o instanceof Node) || !g.containsTuple( f = (Node) o ) ) {
                return;
            }
            f = (Node) o;
            break;
        }

        String filePath = AllComponents.getHtmlRootFolderPath()
                + f.get( "path" );
        final FileTree tree = AllComponents.getFileTree();
        final String finalFilePath = filePath.replace( '/', '\\' );
//        System.out.println( "filtered with file separator path: " + filePath );
        
        // Swing is essentially single threaded. It relies on an 
        // event dispatch thread to handle actions from multiple
        // threads. 
        //
        // Without this, we run into deadlock problems. 
        // Please read and understanding how a tool (Swing) works 
        // before coding up stuff! 
        SwingUtilities.invokeLater(new Runnable() {
        	public void run() {
        		tree.expandTreeByPath( finalFilePath, false );
        	}
        });
        
    }
}
